package com.gitee.apanlh.util.net.http.handler;

import com.gitee.apanlh.exp.HttpConfigException;
import com.gitee.apanlh.exp.HttpException;
import com.gitee.apanlh.util.base.StringUtils;
import com.gitee.apanlh.util.net.http.BaseHttpConfigure;
import com.gitee.apanlh.util.net.http.HttpBody;
import com.gitee.apanlh.util.net.http.HttpClient;
import com.gitee.apanlh.util.net.http.HttpConfig;
import com.gitee.apanlh.util.net.http.HttpRequest;
import com.gitee.apanlh.util.net.http.handler.body.cast.HttpRequestBodyCast;
import com.gitee.apanlh.util.valid.ValidParam;
import com.gitee.apanlh.web.http.HttpContentType;

import java.net.HttpURLConnection;

/**
 * 	HTTP配置拦截器，装配实现对HTTP请求体媒体类型处理
 * 	
 * 	@author Pan
 */
public class HttpContentTypeConfigureChain implements HttpRequestInterceptor, BaseHttpConfigure {
	
	@Override
	public HttpRequest chain(HttpRequest httpRequest, HttpClient httpClient, HttpRequestBodyCast bodyCast, HttpInterceptorChain chain) throws HttpException {
		return chain.proceed(configure(httpRequest, httpClient), httpClient);
	}
	
	@Override
	public HttpRequest configure(HttpRequest httpRequest, HttpClient httpClient) throws HttpConfigException {
		HttpConfig httpConfig = httpRequest.getConfig();
		HttpBody httpBody = httpRequest.getBody();
		HttpURLConnection client = httpClient.getClient();
		
		if (ValidParam.isNotNull(httpBody)) {
			//	Content-Type
			if (httpBody.hasJson()) {
				if (ValidParam.isEmpty(httpConfig.getCharset())) {
					client.setRequestProperty(HttpContentType.CONTENT_TYPE, HttpContentType.APPLICATION_JSON.getType());
				} else {
					client.setRequestProperty(HttpContentType.CONTENT_TYPE, HttpContentType.append(HttpContentType.APPLICATION_JSON, StringUtils.append("charset=", httpConfig.getCharset())));
				}
			} 
			if (httpBody.hasForm()) {
				client.setRequestProperty(HttpContentType.CONTENT_TYPE, HttpContentType.APPLICATION_FORM_URLENCODED.getType());
			}
			if (httpBody.hasFormData()) {
				client.setRequestProperty(HttpContentType.CONTENT_TYPE, HttpContentType.append(HttpContentType.MULTIPART_FORM_DATA, StringUtils.append("boundary=", httpBody.getFormDataBoundary())));
			}
		}
		return httpRequest;
	}
}
